
fabric.Object.prototype.originX = fabric.Object.prototype.originY =
    "center";

fabric.Object.prototype.objectCaching = false;
console.log(window.fabric);


//Done 优化库
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23];
    var uuid = s.join("");
    return uuid;
}
function makeLine(coords, startId, endId) {
    let line = new fabric.Line(coords, {
        id: uuid(),
        fill: "red",
        stroke: "red",
        strokeWidth: 5,
        selectable: false,
        evented: false,
    });
    line.start = startId;
    line.end = endId;
    console.log("makeLine", line);
    return line;
}
function makeCircle(left, top, lines) {
    var c = new fabric.Circle({
        id: uuid(),
        left: left,
        top: top,
        strokeWidth: 5,
        radius: 12,
        fill: "#fff",
        stroke: "#666",
    });

    c.hasControls = true;
    c.hasBorders = false;

    c.controls["addPoint"] = makeNewNavPointControl(function () { });

    c.lines = lines;

    console.log("makeCircle", c);
    return c;
}
let makeNavigationControl = function (obj, callback) {
    let control = new fabric.Control({
        // x和y设置该控制点和第二列中间的控制点重合
        x: 0,
        y: -0.5,
        // offsetX和offsetY设置该控制点在水平和竖直两个方向上
        // 偏移的距离（单位px）
        offsetX: 28,
        offsetY: -20,
        // 光标移动到该控制点时变为一个手的图标
        cursorStyle: "pointer",
        // 自定义的值，可忽略
        actionName: "naviTo",
        // 设置当点击了该控制点，鼠标弹起是执行的动作处理方法
        mouseUpHandler: function (param) {
            callback(obj);
        },
        // render: renderIcon("+"),
        cornerSize: 16,
    });
    return control;
};
let makeDeleteControl = function (obj, callback) {
    let control = new fabric.Control({
        // x和y设置该控制点和第二列中间的控制点重合
        x: 0,
        y: -0.5,
        // offsetX和offsetY设置该控制点在水平和竖直两个方向上
        // 偏移的距离（单位px）
        offsetX: -28,
        offsetY: -20,
        // 光标移动到该控制点时变为一个手的图标
        cursorStyle: "pointer",
        // 自定义的值，可忽略
        actionName: "delete",
        // 设置当点击了该控制点，鼠标弹起是执行的动作处理方法
        mouseUpHandler: function (param) {
            callback(obj);
        },
        // render: renderIcon("+"),
        cornerSize: 16,
    });
    return control;
};
let makeNewNavPointControl = function (callback) {
    let c = new fabric.Control({
        // x和y设置该控制点和第二列中间的控制点重合
        x: 0,
        y: -0.5,
        // offsetX和offsetY设置该控制点在水平和竖直两个方向上
        // 偏移的距离（单位px）
        offsetX: 10,
        offsetY: -10,
        // 光标移动到该控制点时变为一个手的图标
        cursorStyle: "pointer",
        // 自定义的值，可忽略
        actionName: "addPoint",
        // 设置当点击了该控制点，鼠标弹起是执行的动作处理方法
        mouseUpHandler: function (param) {
            let offset = 50;

            let activeInstance = window.canvas.getActiveObject();
            var circleEnd = makeCircle(
                activeInstance.left + offset,
                activeInstance.top + offset,
                []
            );
            window.canvas.add(circleEnd);
            var newLine = makeLine(
                [
                    activeInstance.left,
                    activeInstance.top,
                    circleEnd.left,
                    circleEnd.top,
                ],
                activeInstance.id,
                circleEnd.id
            );
            window.canvas.add(newLine);
            activeInstance.lines.push(newLine.id);
            circleEnd.lines.push(newLine.id);
            window.canvas.renderAll();
            callback();
        },
        // render: renderIcon("+"),
        cornerSize: 16,
    });
    return c;
};
var getObjectById = function (id) {
    var objects = window.canvas._objects;
    var result;
    for (let i = 0; i < objects.length; i++) {
        const obj = objects[i];
        if (obj.id == id) {
            result = obj;
        }
    }
    return result;
};

class ConnectPointAction {
    constructor() {
        this.startPoint = false;
        this.endPoint = false;
    }
}
let cpa = false; //连接两个点的操作实例

class DjPoint {
    constructor(id) {
        this.id = id;
        this.point = getObjectById(id);
        this.distance = 0;
        this.routes = [];
    }
    jointPoint(target) {
        console.log("targetid", target.point.id);
        console.log("this id", this.id);
        // 使用曼哈顿距离算法
        let dx = Math.abs(target.point.left - this.point.left);
        let dy = Math.abs(target.point.top - this.point.top);
        let distance = dx + dy;
        // console.log("原routes", target.routes);
        this.routes = target.routes.concat([this.id]);
        // console.log("新routes", this.routes);
        this.distance = target.distance + distance;
        // console.log("距离:", distance);
    }
}

Array.prototype.distanceBubbleSort = function () {
    for (let i = 0; i < this.length - 1; i += 1) {
        //通过 this.length 次把第一位放到最后,完成排序
        //-i是因为最后的位置是会动态改变的，当完成一次后,最后一位会变成倒数第二位
        for (let j = 0; j < this.length - 1 - i; j += 1) {
            if (this[j].distance > this[j + 1].distance) {
                const temp = this[j];
                this[j] = this[j + 1];
                this[j + 1] = temp;
            }
        }
    }
};

let findMinDistancePoint = function (machine, points) {
    var minDistance = -1; //最小距离
    var targetPoint; //找到的距离更小的点
    machine = getObjectById(machine.id)
    for (let i = 0; i < points.length; i++) {
        const point = points[i];
        let sx = machine.left;
        let sy = machine.top;
        let tx = point.left;
        let ty = point.top;
        let xdist = sx - tx;
        let ydist = sy - ty;
        let dist = Math.sqrt(xdist * xdist + ydist * ydist);
        if (minDistance == -1) {
            minDistance = dist;
            targetPoint = point;
        } else {
            if (dist < minDistance) {
                minDistance = dist;
                targetPoint = point;
            }
        }
    }
    console.log(
        "计算出的minDistance:",
        minDistance,
        "点:",
        targetPoint.left,
        targetPoint.top
    );
    let result = { minDistance: minDistance, targetPoint: targetPoint, targetPointId: targetPoint.id };
    return result;
};

let checkInList = function (checkPoint, closedlist) {
    let result = { result: false, index: -1 };
    for (let i = 0; i < closedlist.length; i++) {
        const cp = closedlist[i];
        if (checkPoint.id == cp.id) {
            result.result = cp;
            result.index = i;
        }
    }
    return result;
};

export { uuid, makeLine, makeCircle,makeDeleteControl, makeNavigationControl, makeNewNavPointControl, getObjectById, ConnectPointAction, DjPoint, findMinDistancePoint, checkInList }